package com.weixing.mall.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.provider.api.model.enums.ActTypeEnum;
import com.weixing.mall.provider.mapper.ActivityMapper;
import com.weixing.mall.provider.model.domain.Activity;
import com.weixing.mall.provider.model.domain.ActivityGoods;
import com.weixing.mall.provider.model.dto.act.ActivityDto;
import com.weixing.mall.provider.model.enums.IsPublishEunm;
import com.weixing.mall.provider.model.enums.act.ActStatusEnum;
import com.weixing.mall.provider.model.enums.act.SettleStatusEnum;
import com.weixing.mall.provider.model.enums.act.UpOrDownEnum;
import com.weixing.mall.provider.model.query.ActivityQuery;
import com.weixing.mall.provider.model.query.act.ActGoodsQuery;
import com.weixing.mall.provider.model.vo.act.ActivityFormVo;
import com.weixing.mall.provider.model.vo.act.ActivityVo;
import com.weixing.mall.provider.service.IActivityGoodsService;
import com.weixing.mall.provider.service.IActivityService;
import com.weixing.mall.redis.RedisKeyConst;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 促销模块-活动表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-16
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    @Autowired
    private IActivityGoodsService activityGoodsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public IPage<ActivityVo> findList(Page initMpPage, ActivityQuery query) {
        //查询会员可以查看的活动
        return baseMapper.findList(initMpPage, query);

    }

    @Override
    public IPage findFrontList(Page initMpPage, ActivityQuery query) {
        return baseMapper.findFrontList(initMpPage,query);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(ActivityDto dto) {
        Activity activity = new Activity();
        BeanUtils.copyProperties(dto,activity);
        activity.setShowClient(dto.getShowClient().getValue());
        activity.setIsDayAct(dto.getIsDayAct().getValue());
        activity.setActType(dto.getActType().getValue());
        if (null == dto.getId()) {
            activity.setIsPublish(IsPublishEunm.NOT_PUBLISH.getValue());
            activity.setActStatus(ActStatusEnum.NOT_START.getValue());
            activity.setSettleStatus(SettleStatusEnum.NOT_SETTLE.getValue());
            save(activity);
            activity.setUrl("http://lm.weixingshishang.cn/#/pages/shop/commodity/list?actId="+activity.getId()+"&actType="+activity.getActType());
            updateById(activity);
        } else {
            activity.setUrl("http://lm.weixingshishang.cn/#/pages/shop/commodity/list?actId="+activity.getId()+"&actType="+activity.getActType());
            updateById(activity);
        }
    }

    @Override
    public List<ActivityFormVo> selectActivityFormVoList(ActTypeEnum actTypeEnum) {
        return baseMapper.selectActivityFormVoList(actTypeEnum);
    }

    /**
     * 查询可用的活动
     * @return
     */
    @Override
    public List<ActivityVo> selectAvailable() {

        return baseMapper.selectAvailable();
    }

    /**
     * 查询可用的活动
     * @return
     */
    @Override
    public List<ActivityVo> selectDataList(Date date,Integer flag) {
        return baseMapper.selectDataList(date,flag);
    }

    /**
     * 方法描述: 预刷新活动商品库存到redis
     * @Author Small
     * @param actId
     * @Date 2020/4/10 12:00
     * @return void
     */
    @Override
    public void refreshStockInRedis(Long actId) {
        List<ActivityGoods> activityGoods = activityGoodsService.findByActId(actId);
        if (!CollUtil.isEmpty(activityGoods)) {
            redisTemplate.executePipelined((RedisCallback<?>) connection -> {
                activityGoods.forEach(item -> {
                    String key = StrUtil.format(RedisKeyConst.ACT_ITEM_STOCK, actId, item.getProductId());
                    byte[] rawKey = redisTemplate.getKeySerializer().serialize(key);
                    connection.set(rawKey, redisTemplate.getValueSerializer().serialize(item.getProductCount()));
                });
                return null;
            });
        }
    }

    /**
     * 方法描述: 活动结束将redis中预刷新的key清除
     * @Author Small
     * @param actId
     * @Date 2020/4/11 9:17
     * @return void
    */
    @Override
    public void delStockFromRedis(Long actId) {
        String preKey = StrUtil.format(RedisKeyConst.ACT_ITEM_STOCK_PRE, actId);
        Set<String> keys = redisTemplate.keys(preKey);
        if (CollUtil.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }

    @Override
    public List<ActivityVo> memnerList(ActivityQuery query) {
        return baseMapper.findMemberList(query);
    }

    @Override
    public List<ActivityVo> selectinvitedList(Date dateTime) {
        return baseMapper.selectinvitedList(dateTime);
    }

    @Override
    public List<ActivityVo> dayList(Integer value) {
        return baseMapper.selectActList(value);
    }

    @Override
    public boolean checkActCode(String actCode) {
        if(ObjectUtil.isEmpty(actCode)){
            return  false;
        }
        if(actCode.length()!=1){
            return  false;
        }
        int a=actCode.charAt(0);
        if(a>='A'&&a<='Z'){
            return  true;
        }
        return false;
    }

    @Override
    public void checkIsDown(ActGoodsQuery query) {
        Long actId=query.getActId();
        Activity activity=getById(actId);
        if(activity.getEndTime().getTime()-new Date().getTime()<0){
            activityGoodsService.update(new UpdateWrapper<ActivityGoods>().eq("act_id",actId).set("up_down", UpOrDownEnum.DOWM.getValue()) );
        }
    }
}
